package com.bocloud.cmp.dao.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.stereotype.Repository;
import org.springframework.util.StringUtils;

import com.bocloud.cmp.dao.ServerDao;
import com.bocloud.cmp.entity.resource.Rack;
import com.bocloud.cmp.entity.resource.Room;
import com.bocloud.cmp.entity.resource.Server;
import com.bocloud.cmp.model.RackDevice;
import com.bocloud.common.model.Param;
import com.bocloud.common.model.SimpleBean;
import com.bocloud.common.utils.Common;
import com.bocloud.common.utils.MapTools;
import com.bocloud.database.core.intf.impl.JdbcGenericDao;
import com.bocloud.database.utils.SQLHelper;

/**
 * 物理服務器DAO接口实现类
 * 
 * @author wei wei
 * @version 1.0
 * @since 2016.02.27
 *
 */
@Repository("serverDao")
public class ServerDaoImpl extends JdbcGenericDao<Server, Long> implements ServerDao {

	@Override
	public Server query(Long id) throws Exception {
		String sql = "select a.*,b.name rackname from server a left join rack b on a.rack_id = b.id where a.is_deleted = 0 and a.id = :id";
		Map<String, Object> params = MapTools.simpleMap("id", id);
		List<Server> list = this.list(Server.class, sql, params);
		if (list.isEmpty()) {
			return null;
		}
		return list.get(0);
	}

	@Override
	public List<Server> list(int page, int rows, List<Param> params, Map<String, String> sorter) throws Exception {
		String sql = "select a.*,b.name rackname,c.name roomname from server a left join rack b on a.rack_id = b.id left join room c on b.room_id = c.id where a.is_deleted = 0";
		sql = SQLHelper.buildSql(sql, page, rows, params, sorter, "a");
		Map<String, Object> paramMap = SQLHelper.getParam(params);
		return this.list(Server.class, sql, paramMap);
	}

	@Override
	public List<SimpleBean> list(List<Param> params, Map<String, String> sorter) throws Exception {
		String sql = "select a.id,a.name from server a where a.is_deleted = 0";
		sql = SQLHelper.buildSql(sql, 1, Integer.MAX_VALUE, params, sorter, "a");
		Map<String, Object> paramMap = SQLHelper.getParam(params);
		List<Server> servers = this.list(Server.class, sql, paramMap);
		List<SimpleBean> beans = new ArrayList<SimpleBean>();

		for (Server server : servers) {
			beans.add(new SimpleBean(server.getId(), server.getName()));
		}
		return beans;
	}

	@Override
	public boolean release(Long id, Long userId) throws Exception {
		String sql = "update server set rack_id = null,gmt_modify = :gmtModify,mender_id = :menderId where is_deleted = 0 and id = :id";
		Map<String, Object> params = MapTools.simpleMap("id", id);
		params.put("menderId", userId);
		params.put("gmtModify", new Date());
		return this.execute(sql, params) > 0;
	}

	@Override
	public boolean belong(RackDevice rackDevice, Long userId) throws Exception {
		String sql = "update server set slot_start = :slotStart,slot_num = :slotNum,rack_id = :rackId,gmt_modify = :gmtModify,mender_id = :menderId where is_deleted = 0 and id = :id";
		Map<String, Object> params = MapTools.simpleMap("id", rackDevice.getDeviceId());
		params.put("rackId", rackDevice.getDeviceId());
		params.put("slotStart", rackDevice.getSlotStart());
		params.put("slotNum", rackDevice.getSlotNum());
		params.put("menderId", userId);
		params.put("gmtModify", new Date());
		return this.execute(sql, params) > 0;
	}

	@Override
	public List<Server> listFree() throws Exception {
		String sql = "select * from server where is_deleted = 0 and rack_id is null";
		return this.list(Server.class, sql);
	}
	
	@Override
	public List<Server> queryAll() throws Exception {
		String sql  = "select * from server where is_deleted = 0";
		return this.list(Server.class, sql);
	}

	@Override
	public int count(List<Param> params) throws Exception {
		String sql = "select count(1) from server a where a.is_deleted = 0";
		sql = SQLHelper.buildSql(sql, params, null, "a");
		Map<String, Object> paramMap = SQLHelper.getParam(params);
		return this.countQuery(sql, paramMap).intValue();
	}

	@Override
	public boolean remove(Long id, Long userId) throws Exception {
		String sql = "update server set is_deleted = true,gmt_modify = :gmtModify,mender_id = :menderId where is_deleted = 0 and id = :id";
		Map<String, Object> params = MapTools.simpleMap("id", id);
		params.put("menderId", userId);
		params.put("gmtModify", new Date());
		return this.execute(sql, params) > 0;
	}

	@Override
	public boolean isolate(Long id, Long userId) throws Exception {
		String sql = "update server set status = :status,gmt_modify = :gmtModify,mender_id = :menderId where is_deleted = 0 and id = :id";
		Map<String, Object> params = MapTools.simpleMap("id", id);
		params.put("menderId", userId);
		params.put("gmtModify", new Date());
		params.put("status", "ISOLATE");
		return this.execute(sql, params) > 0;
	}

	@Override
	public boolean recover(Long id, Long userId) throws Exception {
		String sql = "update server set status = :status,gmt_modify = :gmtModify,mender_id = :menderId where is_deleted = 0 and id = :id";
		Map<String, Object> params = MapTools.simpleMap("id", id);
		params.put("menderId", userId);
		params.put("gmtModify", new Date());
		params.put("status", "RUNNING");
		return this.execute(sql, params) > 0;
	}

	@Override
	public boolean exists(String ip) throws Exception {
		String sql = "select * from server a where a.is_deleted = 0 and a.manager_ip = :ip";
		Map<String, Object> params = MapTools.simpleMap("ip", ip);
		List<Server> list = this.list(Server.class, sql, params);
		return !list.isEmpty();
	}

	@Override
	public List<Server> listFreeNode(Long id, Class<?> clazz) throws Exception {
		String sql = "";
		if (clazz == Rack.class) {
			sql = "select * from server a where not exists(select * from cluster_node b where b.type = 'PM' and a.id = b.node_id) "
					+ "and not exists(select * from resource c where c.type = 'PM' and a.id = c.res_id) and a.is_deleted = 0 and a.rack_id = :id";
		} else if (clazz == Room.class) {
			sql = "select * from server a where not exists(select * from cluster_node b where b.type = 'PM' and a.id = b.node_id) "
					+ "and not exists(select * from resource c where c.type = 'PM' and a.id = c.res_id) and "
					+ "exists(select * from room d,rack r where a.rack_id = r.id and r.room_id = d.id and d.id = :id) and a.is_deleted = 0";
		} else {
			sql = "select * from server a where not exists(select * from cluster_node b where b.type = 'PM' and a.id = b.node_id) "
					+ "and not exists(select * from resource c where c.type = 'PM' and a.id = c.res_id) and "
					+ "exists(select * from data_center f,room d,rack r where a.rack_id = r.id and r.room_id = d.id and d.dc_id = f.id and f.id = :id ) and a.is_deleted = 0";
		}

		Map<String, Object> params = MapTools.simpleMap("id", id);
		return this.list(Server.class, sql, params);
	}

	@Override
	public List<Server> listFreeManager(Long id, Class<?> clazz) throws Exception {
		String sql = "";
		if (clazz == Rack.class) {
			sql = "select * from server a where not exists(select * from cluster_manager b where b.type = 'PM' and a.id = b.manager_id) "
					+ "and not exists(select * from resource c where c.type = 'PM' and a.id = c.res_id) and a.is_deleted = 0 and a.rack_id = :id";
		} else if (clazz == Room.class) {
			sql = "select * from server a where not exists(select * from cluster_manager b where b.type = 'PM' and a.id = b.manager_id) "
					+ "and not exists(select * from resource c where c.type = 'PM' and a.id = c.res_id) and "
					+ "exists(select * from room d,rack r where a.rack_id = r.id and r.room_id = d.id and d.id = :id) and a.is_deleted = 0";
		} else {
			sql = "select * from server a where not exists(select * from cluster_manager b where b.type = 'PM' and a.id = b.manager_id) "
					+ "and not exists(select * from resource c where c.type = 'PM' and a.id = c.res_id) and "
					+ "exists(select * from data_center f,room d,rack r where a.rack_id = r.id and r.room_id = d.id and d.dc_id = f.id and f.id = :id ) and a.is_deleted = 0";
		}

		Map<String, Object> params = MapTools.simpleMap("id", id);
		return this.list(Server.class, sql, params);
	}

	@Override
	public Server get(String ip) throws Exception {
		String sql = "select * from server a where a.is_deleted = 0 and a.manager_ip = :ip";
		Map<String, Object> params = MapTools.simpleMap("ip", ip);
		List<Server> list = this.list(Server.class, sql, params);
		if (list.isEmpty()) {
			return null;
		}
		return list.get(0);
	}

	@Override
	public List<String> DcIps(Long dcId) throws Exception {
		String sql = "select a.manager_ip from server a,rack b,room c,data_center d where a.is_deleted = 0 and a.rack_id = b.id and b.room_id = c.id and c.dc_id = d.id and d.id = :dcId";
		Map<String, Object> params = MapTools.simpleMap("dcId", dcId);
		List<Server> list = this.list(Server.class, sql, params);
		List<String> result = new ArrayList<String>();
		for (Server server : list) {
			result.add(server.getManagerIp());
		}
		return result;
	}

	@Override
	public List<String> ips() throws Exception {
		String sql = "select manager_ip from server  where is_deleted = 0";
		List<Server> list = this.list(Server.class, sql);
		List<String> result = new ArrayList<String>();
		for (Server server : list) {
			result.add(server.getManagerIp());
		}
		return result;
	}

	@Override
	public List<String> rackIps(Long rackId) throws Exception {
		String sql = "select DISTINCT(a.manager_ip) from server a,rack b where a.is_deleted = 0 and a.rack_id = b.id and b.id = :rackId";
		Map<String, Object> params = MapTools.simpleMap("rackId", rackId);
		List<Server> list = this.list(Server.class, sql, params);
		List<String> result = new ArrayList<String>();
		for (Server server : list) {
			result.add(server.getManagerIp());
		}
		return result;
	}

	@Override
	public List<String> roomIps(Long roomId) throws Exception {
		String sql = "select DISTINCT(a.manager_ip) from server a,rack b,room c where a.is_deleted = 0 and a.rack_id = b.id and b.room_id = c.id and c.id = :roomId";
		Map<String, Object> params = MapTools.simpleMap("roomId", roomId);
		List<Server> list = this.list(Server.class, sql, params);
		List<String> result = new ArrayList<String>();
		for (Server server : list) {
			result.add(server.getManagerIp());
		}
		return result;
	}

	@Override
	public List<String> dcIps(Long dcId) throws Exception {
		String sql = "SELECT DISTINCT(a.manager_ip) FROM server a,rack b,room c,data_center d WHERE a.is_deleted = 0 AND a.rack_id = b.id AND b.room_id = c.id AND c.dc_id = d.id AND d.id = :dcId ";
		Map<String, Object> params = MapTools.simpleMap("dcId", dcId);
		List<Server> list = this.list(Server.class, sql, params);
		List<String> result = new ArrayList<String>();
		for (Server server : list) {
			result.add(server.getManagerIp());
		}
		return result;
	}

	@Override
	public List<String> nodeIps(Long clusterId) throws Exception {
		String sql = "select a.manager_ip from server a,cluster_node b,cluster c where a.is_deleted = 0 and a.id = b.node_id and b.cluster_id = c.id and c.id = :clusterId";
		Map<String, Object> params = MapTools.simpleMap("clusterId", clusterId);
		List<Server> list = this.list(Server.class, sql, params);
		List<String> resutl = new ArrayList<String>();
		for (Server server : list) {
			resutl.add(server.getManagerIp());
		}
		return resutl;
	}

	@Override
	public List<String> managerIps(Long clusterId) throws Exception {
		String sql = "select a.manager_ip from server a,cluster_manager b,cluster c where a.is_deleted = 0 and a.id = b.manager_id and b.cluster_id = c.id and c.id = :clusterId";
		Map<String, Object> params = MapTools.simpleMap("clusterId", clusterId);
		List<Server> list = this.list(Server.class, sql, params);
		List<String> resutl = new ArrayList<String>();
		for (Server server : list) {
			resutl.add(server.getManagerIp());
		}
		return resutl;
	}

	@Override
	public List<RackDevice> positions(Long rackId, String sorter) throws Exception {
		String sql = "select a.id,a.slot_start,a.slot_num from server a where a.is_deleted = 0 and a.rack_id = :rackId";
		if (sorter.equals(Common.ZERO)) {
			sql += " order by a.slot_start asc";
		} else {
			sql += " order by a.slot_start desc";
		}
		Map<String, Object> paramMap = MapTools.simpleMap("rackId", rackId);
		List<Map<String, Object>> devices = this.list(sql, paramMap);
		List<RackDevice> list = new ArrayList<RackDevice>();
		for (Map<String, Object> map : devices) {
			RackDevice device = new RackDevice();
			device.setDeviceId(Long.parseLong(map.get(Common.ID.toUpperCase()).toString()));
			device.setRackId(rackId);
			device.setSlotNum(Integer.parseInt(map.get("slot_start").toString()));
			device.setSlotStart(Integer.parseInt(map.get("slot_num").toString()));
			list.add(device);
		}
		return list;
	}

	@Override
	public List<Map<String, String>> getAll4Snmp() throws Exception {
		String sql = "select uuid,manager_ip from server where is_deleted = 0";
		List<Server> servers = this.list(Server.class, sql);

		List<Map<String, String>> result = new ArrayList<>();
		Map<String, String> map;
		String ip;

		for (Server server : servers) {
			ip = server.getManagerIp();
			if (StringUtils.isEmpty(ip)) {
				continue;
			}

			map = new HashMap<>();
			map.put("uuid", server.getUuid());
			map.put("ip", ip);
			result.add(map);
		}

		return result;
	}

	@Override
	public List<Server> listByDataCenter(Long dcId) throws Exception {
		String sql = "select a.* from server a left join rack b on a.rack_id = b.id left join room c on b.room_id = c.id where a.is_deleted = 0 and c.dc_id = '"
				+ dcId + "'";
		return this.list(Server.class, sql);
	}

	@Override
	public List<Server> listByRoom(Long roomId) throws Exception {
		String sql = "select a.* from server a left join rack b on a.rack_id = b.id where a.is_deleted = 0 and b.room_id = '"
				+ roomId + "'";
		return this.list(Server.class, sql);
	}

	@Override
	public List<Server> listByRack(Long rackId) throws Exception {
		String sql = "select a.* from server a where a.is_deleted = 0 and a.rack_id = '" + rackId + "'";
		return this.list(Server.class, sql);
	}

}
